//
//  MKScrollNews.m
//  NewsReader
//
//  Created by 杨乐 on 16/5/2.
//  Copyright © 2016年 GaoSir_. All rights reserved.
//

#import "MKScrollNews.h"

static int const circlePage = 3;

@interface MKScrollNews() <UIScrollViewDelegate>
@property (weak, nonatomic) UIScrollView *scrollView;
@property (weak, nonatomic) UIPageControl *pageView;
/** 自动切换计时器 */
@property (nonatomic, weak) NSTimer * timer;
/** block */
@property (nonatomic, strong) void(^myBlock)(NSInteger index);
@end

@implementation MKScrollNews

#pragma mark - 初始化
- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        UIScrollView *scrollView = [[UIScrollView alloc] init];
        scrollView.showsHorizontalScrollIndicator = NO;
        scrollView.showsVerticalScrollIndicator = NO;
        scrollView.pagingEnabled = YES;
        scrollView.bounces = NO;
        scrollView.delegate = self;
        [self addSubview:scrollView];
        self.scrollView = scrollView;
        
        for (int i = 0; i<circlePage; i++) {
            UIImageView *imageView = [[UIImageView alloc] init];
            [scrollView addSubview:imageView];
        }
        
        UIPageControl *pageControl = [[UIPageControl alloc] init];
        [self addSubview:pageControl];
        _pageView = pageControl;
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
        [self.scrollView addGestureRecognizer:tap];
    }
    return self;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    float H = self.frame.size.height;
    float W = self.frame.size.width;
    self.scrollView.frame = CGRectMake(0, 0, W, H);
    self.scrollView.contentSize = CGSizeMake(circlePage * W, 0);
    self.scrollView.contentOffset = CGPointMake(W, 0);
    for (int i=0; i<circlePage; i++) {
        UIImageView *imageView = self.scrollView.subviews[i];
        imageView.frame = CGRectMake(W * i, 0, W, H);
    }
    
    self.pageView.frame = CGRectMake(W-100, H-20, 100, 20);
    self.pageView.hidesForSinglePage = YES;
    self.pageView.pageIndicatorTintColor = [UIColor lightGrayColor];
    self.pageView.currentPageIndicatorTintColor = [UIColor redColor];
    self.pageView.currentPage = 0;
}

- (void)tapAction:(UITapGestureRecognizer *)tap
{
    if (self.myBlock) {
        self.myBlock(self.pageView.currentPage);
    }
}

- (void)callBack:(void (^)(NSInteger))block{
    self.myBlock = block;
}

+ (instancetype)pageView{
    return [self xib];
}

- (BOOL)hasData
{
    return self.images && self.images.count>1;
}

#pragma mark - set方法
- (void)setImages:(NSArray *)images
{
    _images = images;
    self.pageView.numberOfPages = images.count;

    [self updateContent];
    [self startTimer];
}

- (void)updateContent
{
    for (int i = 0; i<self.scrollView.subviews.count; i++) {
        UIImageView *imageView = self.scrollView.subviews[i];
        NSInteger index = self.pageView.currentPage;
        if (i == 0) {
            index--;
        } else if (i == 2) {
            index++;
        }
        if (index < 0) {
            index = self.pageView.numberOfPages - 1;
        } else if (index >= self.pageView.numberOfPages) {
            index = 0;
        }
        imageView.tag = index;
        imageView.image = self.images[index];
    }
    self.scrollView.contentOffset = CGPointMake(self.scrollView.frame.size.width, 0);
}

#pragma mark - 计时器
- (void)startTimer
{
    NSTimer *timer = [NSTimer timerWithTimeInterval:2 target:self selector:@selector(nextStep) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    self.timer = timer;
}

- (void)stopTimer
{
    [self.timer invalidate];
    self.timer = nil;
}

- (void)nextStep
{
    [self.scrollView setContentOffset:CGPointMake(self.scrollView.frame.size.width * 2, 0) animated:YES];
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    //找出最中间的那个图片控件
    NSInteger page = 0;
    CGFloat minDistance = MAXFLOAT;
    for (int i = 0; i<self.scrollView.subviews.count; i++) {
        UIImageView *imageView = self.scrollView.subviews[i];
        CGFloat distance = 0;
        distance = ABS(imageView.frame.origin.x - scrollView.contentOffset.x);
        if (distance < minDistance) {
            minDistance = distance;
            page = imageView.tag;
        }
    }
    self.pageView.currentPage = page;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    if ([self hasData]) {
        [self stopTimer];
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if ([self hasData]) {
        [self startTimer];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if ([self hasData]) {
        [self updateContent];
    }
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    if ([self hasData]) {
        [self updateContent];
    }
}

@end
